package com.letter.otools.day;

import android.annotation.TargetApi;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.tabs.TabLayout;
import com.letter.otools.day.service.NotifyService;
import com.letter.otools.day.user.AboutUsActivity;
import com.letter.otools.day.user.SettingActivity;
import com.letter.otools.day.util.AnniUtil;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;
import com.yanzhenjie.recyclerview.touch.OnItemMoveListener;

import org.litepal.FluentQuery;
import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MainOldActivity extends BaseActivity {

    private AnniAdapter anniAdapter;

    List<Anniversary> anniversaryList = new ArrayList<>();

    public static boolean isAlive = false;

    private TabLayout tabLayout;

    @Override
    protected int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void onDestroy() {
        isAlive = false;
        super.onDestroy();
    }

    private void initTabLayout() {
        tabLayout.addTab(tabLayout.newTab().setText("All"));
        for (int i = 0; i < Anniversary.typeText.length; i++) {
            tabLayout.addTab(tabLayout.newTab().setText(Anniversary.typeText[i]));
        }
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition() == 0) {
                    loadData(null, true);
                } else {
                    loadData(tab.getPosition() - 1, true);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    OnItemMoveListener mItemMoveListener = new OnItemMoveListener() {
        @Override
        public boolean onItemMove(RecyclerView.ViewHolder srcHolder, RecyclerView.ViewHolder targetHolder) {
            // 此方法在Item拖拽交换位置时被调用。
            // 第一个参数是要交换为之的Item，第二个是目标位置的Item。

            // 交换数据，并更新adapter。
            int fromPosition = srcHolder.getAdapterPosition();
            int toPosition = targetHolder.getAdapterPosition();
            Collections.swap(anniversaryList, fromPosition, toPosition);
            anniAdapter.notifyItemMoved(fromPosition, toPosition);

            // 返回true，表示数据交换成功，ItemView可以交换位置。
            return true;
        }

        @Override
        public void onItemDismiss(RecyclerView.ViewHolder srcHolder) {
            // 此方法在Item在侧滑删除时被调用。
            // 从数据源移除该Item对应的数据，并刷新Adapter。
            int position = srcHolder.getAdapterPosition();
            anniversaryList.remove(position);
            anniAdapter.notifyItemRemoved(position);
        }
    };

    void loadData(Integer type, boolean notify) {
        anniversaryList.clear();
        FluentQuery fluentQuery = LitePal.order("id asc");
        if (type != null) {
            fluentQuery.where("type = ?", String.valueOf(type));
        }
        List<Anniversary> anniversaryList = fluentQuery.find(Anniversary.class);
        if (anniversaryList != null && !anniversaryList.isEmpty()) {
            this.anniversaryList.addAll(anniversaryList);
        }

        if (notify) {
            anniAdapter.notifyDataSetChanged();
        }

        //LitePal.findAll(Anniversary.class);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isAlive = true;
//        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.Toolbar);
        tabLayout = findViewById(R.id.tabLayout);
        setSupportActionBar(toolbar);
        toolbar.setSubtitle("Record important days in your life");
//        toolbar.setTitle("Days,Record important days in your life");
//        this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        initTabLayout();
        loadData(null, false);

        SwipeRecyclerView recyclerView = findViewById(R.id.recycler_view);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new SpacesItemDecoration(1));
        recyclerView.setLongPressDragEnabled(true); // 拖拽排序，默认关闭
        anniAdapter = new AnniAdapter(anniversaryList);

        recyclerView.setOnItemMoveListener(mItemMoveListener);// 监听拖拽，更新UI。

        anniAdapter.setOnAnniItemClickListener(new OnAnniItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Intent intent = new Intent(MainOldActivity.this, AnniversaryActivity.class);
                intent.putExtra("anniId", anniversaryList.get(position).getId());
                startActivityForResult(intent, 1);
            }
        });
        recyclerView.setAdapter(anniAdapter);

        final FloatingActionButton floatingActionButton = findViewById(R.id.fab);
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainOldActivity.this, AddItemActivity.class);
                intent.putExtra("editType", AddItemActivity.ITEM_ADD);
                startActivityForResult(intent, 1);
            }
        });

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelId = "anni";
            String channelName = "Notice";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            createNotificationChannel(channelId, channelName, importance);
        }

//        Intent broadIntent  = new Intent("android.appwidget.action.APPWIDGET_UPDATE");
//        getApplicationContext().sendBroadcast(broadIntent);

        if (AnniUtil.isNotifyServiceRunning(getApplicationContext()) != true) {
            startService(new Intent(this, NotifyService.class));
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    anniversaryList.clear();
                    anniversaryList.addAll(LitePal.findAll(Anniversary.class));
                    anniAdapter.notifyDataSetChanged();
                }
                break;

            default:
                break;
        }
    }

    @TargetApi(Build.VERSION_CODES.O)
    private void createNotificationChannel(String channelId, String channelName, int importance) {
        NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
        NotificationManager notificationManager = (NotificationManager) getSystemService(
                NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(channel);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == R.id.action_settings) {
            startActivity(new Intent(this, SettingActivity.class));
            return true;
        } else if (itemId == R.id.action_About) {
            startActivity(new Intent(this, AboutUsActivity.class));
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
